import axios from "axios";
import store from "@/store/index.js";
import router from "@/route/index.js";
import { toast } from "vant"
class BaseApi {
  baseService;
  constructor({ baseURL, timeout = 15000 }) {
    const baseServiceConfig = {
      baseURL,
      timeout,
    };
    this.baseService = axios.create(baseServiceConfig);
    this._setInterceptorsRequest();
    this._setInterceptorsResponse();
  }
  get(url, params = {}, authorization) {
    return this.request(url, "get", params, {}, authorization);
  }
  post(url, data = {}, authorization, contentType = "application/json", login) {
    return this.request(url, "post", {}, data, authorization, contentType, false, login);
  }
  postImg(url, data = {}, authorization, contentType = "multipart/form-data", transformRequest = true) {
    return this.request(url, "post", {}, data, authorization, contentType, transformRequest);
  }
  postAuth() {}
  request(url, method, params, data, authorization, contentType, transformRequest, login) {
    const headers = {
      "Content-Type": contentType
    };
    if(authorization == 'auth') {
      headers['X-Custom-Auth'] = 'a53ad7e8-aa7d-43cd-8240-07fe174505bf'
      headers['X-Custom-Time'] = Date.now()
    }
    if(!authorization || authorization == 'third') {
      const token = localStorage.getItem("SAVE_TOKEN");
      if (!token) {
        toast.msg("非法请求！")
        router.push("/")
        return Promise.reject("非法请求！");
      } else {
        if(authorization == 'third') {
          // headers.Authorization = 'ThirdBearer ' + token;
          headers.Authorization = 'Bearer ' + token;
        } else {
          headers.Authorization = 'Bearer ' + token;
        }
      }
    } else if(login) {
      return this.baseService({
        method,
        url: url,
        params: params,
        auth: data,
        headers,
        transformRequest: [],
        responseType: "json",
        // 允许为上传处理进度事件
        onUploadProgress: function (progressEvent) {
          // console.log("progressEvent", progressEvent);
        },
        // 允许为下载处理进度事件
        onDownloadProgress: function (progressEvent) {
          // console.log("progressEvent", progressEvent);
        },
      });
    } else {
      return this.baseService({
        method,
        url: url,
        params: params,
        data: data,
        headers,
        responseType: "json",
        // 允许为上传处理进度事件
        onUploadProgress: function (progressEvent) {
          // console.log("progressEvent", progressEvent);
        },
        // 允许为下载处理进度事件
        onDownloadProgress: function (progressEvent) {
          // console.log("progressEvent", progressEvent);
        },
      });
    }
    if(transformRequest) {
      return this.baseService({
        method,
        url: url,
        params: params,
        data: data,
        headers,
        transformRequest: [],
        responseType: "json",
        // 允许为上传处理进度事件
        onUploadProgress: function (progressEvent) {
          // console.log("progressEvent", progressEvent);
        },
        // 允许为下载处理进度事件
        onDownloadProgress: function (progressEvent) {
          // console.log("progressEvent", progressEvent);
        },
      });
    } else {
      return this.baseService({
        method,
        url: url,
        params: params,
        data: data,
        headers,
        responseType: "json",
        // 允许为上传处理进度事件
        onUploadProgress: function (progressEvent) {
          // console.log("progressEvent", progressEvent);
        },
        // 允许为下载处理进度事件
        onDownloadProgress: function (progressEvent) {
          // console.log("progressEvent", progressEvent);
        },
      });
    }
  }
  // 请求拦截器
  _setInterceptorsRequest() {
    this.baseService.interceptors.request.use(
      config => {
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );
  }
  // 响应拦截器
  _setInterceptorsResponse() {
    this.baseService.interceptors.response.use(
      function (response) {
        if (response.status >= 200 && response.status <= 299) {
          switch (response.data.code || response.status) {
            case 200:
              return Promise.resolve(response.data);
            case 500:
              return Promise.reject(response.data);
            case 400:
              return Promise.reject(response.data.message);
            case 401:
              toast(response.data.message)
              localStorage.removeItem("ZAYY_USER_INFO")
              router.push("/")
              return Promise.reject(response.data.message);
            default:
              toast.msg(response.data)
              return Promise.resolve(response.data);
          }
        }
        return Promise.reject("error");
      },
      (error) => {
        const token = localStorage.getItem("SAVE_TOKEN");
        if(token) {
          if(error.response.status == 401) {
            alert("登录已过期！")
            localStorage.removeItem("SAVE_TOKEN")
            const currentRoute = router.currentRoute.value;
      
            // 针对 point-forms 页面的特殊处理
            if (currentRoute.path.startsWith('/point-forms/')) {
              // 提取 ID 和查询参数
              const id = currentRoute.path.split('/')[2]; // 获取 /point-forms/123 中的 123
              const query = { ...currentRoute.query }; // 复制所有查询参数（如 corpId）
              
              // 跳转到首页，携带特定格式的 redirect 参数
              router.replace({
                path: '/',
                query: {
                  redirect: 'point-forms',
                  qrCode: id, // 将 ID 作为 qrCode 参数
                  ...query    // 保留原有的查询参数（如 corpId）
                }
              });
            } else {
              // 其他页面的默认处理（可保持原有逻辑）
              router.replace('/');
            }
            return Promise.reject(error)
          }          
        }
        return Promise.reject(error.response.data);
      }
    );
  }
}
export default new BaseApi({ baseURL: `${process.env.APP_BASE_URL}`});
